﻿using System;
using System.Collections.Generic;

using System.Text;
using System.Xml.Serialization;
using System.Web.UI;
using System.IO;
using System.ComponentModel;
using System.Xml;
using System.Web;
using Portal.Environment;
using Portal.Language;
using Portal.Interface;
using System.Data;
using System.Data.SqlClient;

namespace Portal.CDSP
{
    public class FSiteStatisticsWP : WebPart
    {

        #region Properties
        public override void RegAjaxPro(System.Web.UI.Page ActivePage)
        {
            AjaxPro.Utility.RegisterTypeForAjax(typeof(FSiteStatisticsWP), ActivePage);
        }
        public override string WebPartId
        {
            get
            {
                return "WebSite.FSiteStatisticsWP";
            }
        }
        public override string WebPartFolder
        {
            get
            {
                return "Portal.CDSP";
            }
        }
        public override string Title
        {
            get
            {
                return GetText("Title", "Thống kê truy cập");
            }
        }
        public override string NameSpace
        {
            get
            {
                return "Portal.CDSP";
            }
        }
        public override string ClassName
        {
            get
            {
                return "FSiteStatisticsWP";
            }
        }
        public override bool AllowFrontService
        {
            get
            {
                return true;
            }
        }
        public override DataTable ReadingDataService(string belongSite, string ActiveLanguage, ref string IdField, ref string SubjectField)
        {
            IdField = "Id";
            SubjectField = "Subject";
            DataTable dtResult = new DataTable();
            dtResult.Columns.Add("Id");
            dtResult.Columns.Add("Subject");
            dtResult.Rows.Add(new object[]{
                "69EB07FC-EA01-46fe-A1B3-5BDA611C7981","Main"
            });
            return dtResult;
        }
        public override ViewCls[] Views
        {
            get
            {
                return new ViewCls[]{
                    new ViewCls("Main",GetText("SiteStatisticsWebPartMain","Giao diện chính"),1),
                };
            }
        }
        #endregion

        [AjaxPro.AjaxMethod]
        public override string ClientRenderWebPart(string BelongSite, string TabModuleId, string ViewName, string HasPorlet, LoadParamCls loadParamCls)
        {
            try
            {
                if (ViewName.Equals("Main"))
                {
                    return ServerRenderSiteStatisticsWebPartMain(TabModuleId, HasPorlet, BelongSite);
                }
                return GetText("ViewNotFound", "Không tìm thấy View [" + ViewName + "]");
            }
            catch (Exception ex)
            {
                return ex.Message.ToString();
            }


        }

        private SiteStatisticsProperties GetSiteStatistics()
        {
            string SFilePath = Environments.WorkingPath + "\\";

            if (!Directory.Exists(SFilePath + SiteStatisticsProperties.Resources))
            {
                Directory.CreateDirectory(SFilePath + SiteStatisticsProperties.Resources);
                return new SiteStatisticsProperties();
            }
            else if (!File.Exists(SFilePath + SiteStatisticsProperties.Resources + "\\" + SiteStatisticsProperties.XmlFileName))
            {
                return new SiteStatisticsProperties();
            }
            else
            {
                SiteStatisticsProperties stic = XMLHelper.DeserializeFile(SFilePath + SiteStatisticsProperties.Resources + "\\" + SiteStatisticsProperties.XmlFileName, new SiteStatisticsProperties()) as SiteStatisticsProperties;
                return stic;
            }
        }

        private SiteStatisticsProperties GetSiteStatistics(string CurrentIPHost)
        {
            string SFilePath = Environments.WorkingPath + "\\";

            if (!Directory.Exists(SFilePath + SiteStatisticsProperties.Resources))
            {
                Directory.CreateDirectory(SFilePath + SiteStatisticsProperties.Resources);
                return new SiteStatisticsProperties();
            }
            else if (!File.Exists(SFilePath + SiteStatisticsProperties.Resources + "\\" + SiteStatisticsProperties.XmlFileName))
            {
                return new SiteStatisticsProperties();
            }
            else
            {
                SiteStatisticsProperties stic = XMLHelper.DeserializeFile(SFilePath + SiteStatisticsProperties.Resources + "\\" + SiteStatisticsProperties.XmlFileName, new SiteStatisticsProperties()) as SiteStatisticsProperties;
                stic.ClearAllSessionTimeOut();
                if (!stic.OnlineIPStore.Contains(CurrentIPHost))
                {
                    stic.OnlineIPStore.Add(CurrentIPHost);
                    stic.OnlineTimeOutStore.Add(DateTime.Now.ToString());
                }
                return stic;
            }
        }

        private string ServerRenderSiteStatisticsWebPartMain(string TabModuleId, string HasPorlet, string BelongSite)
        {
            StringBuilder _html = new StringBuilder();
            try
            {
                _html.Append(
                                    "<div class=\"side stat\">\n" +
                "					<div class=\"side-head\">\n" +
                "						<h2>Thống kê truy cập</h2>\n" +
                "					</div>\n" +
                "					<div class=\"side-content\">\n" +
                "						<table>\n" +
                "							<tbody>\n" +
                "								<tr>\n" +
                "									<td><p><img src=\"img/user1.png\" />Tổng số:</p></td>\n" +
                "									<td class=\"td-value\">" + HttpContext.Current.Application["Total"].ToString() + "</td>\n" +
                "								</tr>\n" +
                "								<tr>\n" +
                "									<td><p><img src=\"img/user2.png\" />Online:</p></td>\n" +
                "									<td class=\"td-value\">" + HttpContext.Current.Application["visitors_online"].ToString() + "</td>\n" +
                "								</tr>\n" +
                "							</tbody>\n" +
                "						</table>\n" +
                "					</div>\n" +
                "				</div>\n");

                return _html.ToString();
            }
            catch (Exception ex)
            {
                return _html.Append("ERROR:" + ex.Message.ToString()).ToString();
            }
        }
    }



    [Serializable(), XmlRoot(IsNullable = false)]
    public class SiteStatisticsProperties
    {
        [XmlElement]
        public int ViewNumber;
        [XmlElement]
        public int CurrentOnlineNumber;
        public static readonly string Resources = "SiteStatistics";
        public static readonly string XmlFileName = "SiteStatistics.xml";
        [XmlElement]
        public List<string> OnlineIPStore;
        [XmlElement]
        public List<string> OnlineTimeOutStore;
        [XmlElement]
        public List<string> OnlineUser;

        public SiteStatisticsProperties()
        {
            ViewNumber = 0;
            CurrentOnlineNumber = 0;
            OnlineIPStore = new List<string>();
            OnlineTimeOutStore = new List<string>();
        }

        public void ClearAllSessionTimeOut()
        {
            for (int i = 0; i < OnlineTimeOutStore.Count; i++)
            {
                if (DateTime.Now.Subtract(DateTime.Parse(OnlineTimeOutStore[i])).Minutes > 120)
                {
                    OnlineIPStore.RemoveAt(i);
                    OnlineTimeOutStore.RemoveAt(i);
                    OnlineUser.RemoveAt(i);
                }
            }
        }
    }

    public class XMLHelper
    {
        public static void SerializeFile(string path, object xmlclass)
        {
            Serialize(new StreamWriter(path, false), xmlclass);
        }
        public static void Serialize(TextWriter writer, object xmlclass)
        {
            try
            {
                XmlSerializer serializer = new XmlSerializer(xmlclass.GetType());
                serializer.Serialize(writer, xmlclass,
                    new XmlSerializerNamespaces(new List<XmlQualifiedName> { new XmlQualifiedName("", "") }.ToArray()));
            }
            finally
            {
                if (writer != null)
                {
                    writer.Close();
                }
            }
        }
        public static object Deserialize(TextReader reader, object xmlclass)
        {
            try
            {
                XmlSerializer serializer = new XmlSerializer(xmlclass.GetType());
                return (serializer.Deserialize(reader)) as object;
            }
            finally
            {
                if (reader != null)
                {
                    reader.Close();
                }
            }
        }
        public static object DeserializeFile(string Path, object xmlclass)
        {
            return Deserialize(new StreamReader(Path, true), xmlclass);
        }

    }
}
